package storage

import (
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
)

func NewMinio(endpoint, accessKeyID, secretAccessKey, bucketName string, useSSL bool) (*Minio, error) {
	client, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: useSSL,
	})
	if err != nil {
		return nil, err
	}

	return &Minio{client: client, bucketName: bucketName}, nil
}

type Minio struct {
	client     *minio.Client
	bucketName string
}

func (m *Minio) Upload(filePath string, destination string) error {
	_, err := m.client.FPutObject(context.Background(), m.bucketName, destination, filePath, minio.PutObjectOptions{})
	if err != nil {
		return fmt.Errorf("failed to upload file: %v", err)
	}
	return nil
}
func (m *Minio) Delete(objectName string) error {
	err := m.client.RemoveObject(context.Background(), m.bucketName, objectName, minio.RemoveObjectOptions{})
	if err != nil {
		return fmt.Errorf("failed to delete object: %v", err)
	}
	return nil
}
func (m *Minio) Move(source string, destination string) error {
	if err := m.Copy(source, destination); err != nil {
		return err
	}
	return m.Delete(source)
}
func (m *Minio) Copy(source string, destination string) error {
	src := minio.CopySrcOptions{
		Bucket: m.bucketName,
		Object: source,
	}
	dst := minio.CopyDestOptions{
		Bucket: m.bucketName,
		Object: destination,
	}

	_, err := m.client.CopyObject(context.Background(), dst, src)
	if err != nil {
		return fmt.Errorf("failed to copy object: %v", err)
	}
	return nil
}
